import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-10-07
 * Time: 15:10
 */
public class Demo2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要扫描的目录");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if(!rootDir.isDirectory()) {
            System.out.println("您输入的路径不是正确的目录路径，请检查你输入的路径");
            return;
        }

        System.out.println("请输入你要查询的文件名或者文件内容中包含的关键词");
        String word = scanner.next();
        List<File> list = new ArrayList<>();
        scanDir(rootDir,word,list);
        for (File s : list) {
            System.out.println(s.getAbsoluteFile());
        }
    }

    private static void scanDir(File rootDir, String word, List<File> list) {
        File[] files = rootDir.listFiles();
        if (files == null) return;
        for (File f : files) {
            if (f.isDirectory()) {
                scanDir(f,word,list);
            }else {
                if (isContainsContent(f,word)) {
                    list.add(f);
                }
            }
        }
    }

    private static boolean isContainsContent(File f, String word) {
        if (f.getName().contains(word)) return true;
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = new FileInputStream(f.getAbsoluteFile())) {
            try (Scanner scanner = new Scanner(f.getAbsoluteFile())) {
                while (scanner.hasNextLine()) {
                    stringBuilder.append(scanner.nextLine());
                    if (stringBuilder.indexOf(word) != -1) return true;
                }

                return false;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
